package com.hgd.security.evp.biz.biz;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hgd.security.evp.biz.entity.EvpDepart;
import com.hgd.security.evp.biz.entity.EvpUser;
import com.hgd.security.evp.biz.mapper.EvpUserMapper;
import com.hgd.security.evp.biz.vo.EvpUserVo;
import com.hgd.security.evp.common.biz.BusinessBiz;
import com.hgd.security.evp.common.constances.CustomHttpStatus;
import com.hgd.security.evp.common.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author By Shang
 * @version 2019-01-01 22:49:10
 * @email ${email}
 */
@Service
public class EvpUserBiz extends BusinessBiz<EvpUserMapper, EvpUser> {
	@Autowired
	private PasswordEncoder passwordEncoder;

	@Autowired
	private EvpDepartBiz evpDepartBiz;
	/**
	 * 获取某组下的用户
	 *
	 * @param groupId 组ID
	 * @return 某组下的用户
	 */
	public TableResultResponse<JSONObject> getUserOfGroup(Integer groupId) {
		TableResultResponse<JSONObject> tableResult = new TableResultResponse<>();
		List<JSONObject> rows = this.mapper.selectUserOfGroup(groupId);

		if (EmptyUtil.isEmpty(rows)) {
			tableResult.setRows(new ArrayList<>());
		} else {
			tableResult.setRows(rows);
		}

		return tableResult;
	}

	/**
	 * 按用户帐号查询用户
	 * 
	 * @param eAccount 待查询用户帐号
	 * @return 结果
	 */
	public EvpUser getUserByEAccount(String eAccount) {
		Example example=new Example(EvpUser.class).selectProperties(
			"id",
			"evpAccount",
			"evpPassword",
			"isSuper",
			"userName",
			"deptId"
		);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("isDeleted", BooleanUtil.BOOLEAN_FALSE);
		criteria.andEqualTo("evpAccount",eAccount);
		List<EvpUser> evpUsers = this.selectByExample(example);
		if(EmptyUtil.isNotEmpty(evpUsers)){
			return evpUsers.get(0);
		}
		return null;
	}

	/**
	 * 分页获取列表
	 *
	 * @param user
	 * @return
	 */
	public ListResult<EvpUserVo> getUserLiset(EvpUser user, int page, int limit) {
		Example example = new Example(EvpUser.class)
			.selectProperties("id", "evpAccount", "phone", "userName", "addr", "email", "sex", "description","isDeleted","deptId");
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("isDeleted", BooleanUtil.BOOLEAN_FALSE);

		if (StringUtil.isNotBlank(user.getEvpAccount())) {
			criteria.andLike("evpAccount", "%"+user.getEvpAccount()+"%");
		}
		if (StringUtil.isNotBlank(user.getPhone())) {
			criteria.andLike("phone", "%"+user.getPhone()+"%");
		}
		if (StringUtil.isNotBlank(user.getUserName())) {
			criteria.andLike("userName", "%"+user.getUserName()+"%");
		}

		Page<EvpUser> pageInfo = PageHelper.startPage(page, limit);
		List<EvpUser> EvpUsers = this.selectByExample(example);

		List<EvpUserVo> result;
		if (EmptyUtil.isNotEmpty(EvpUsers)) {
			result = BeanUtil.copyBeanListNew(EvpUsers, EvpUserVo.class);
			List<String> collect = result.stream().map(o->String.valueOf(o.getDeptId())).distinct().collect(Collectors.toList());

			List<EvpDepart> deptList = evpDepartBiz.selectbyids(StringUtil.join(collect, ","));

			Map<Integer,String> deptIdNameMap=new HashMap<>();
			if(EmptyUtil.isNotEmpty(deptList)){
				deptIdNameMap=deptList.stream().collect(Collectors.toMap(EvpDepart::getId, EvpDepart::getEvpName));
			}

			Map<Integer, String> finalDeptIdNameMap = deptIdNameMap;
			result.forEach(EvpUserVo -> {
				EvpUserVo.setDeptName(finalDeptIdNameMap.get(EvpUserVo.getDeptId()));
			});
			return new ListResult<>(pageInfo.getTotal(), result);
		}

		return new ListResult<>(0, new ArrayList<>());
	}

	/**
	 * 添加单个对象
	 *
	 * @param user
	 * @return
	 */
	public ObjectResultResponse<Void> addUser(EvpUser user) {
		ObjectResultResponse<Void> restResult = new ObjectResultResponse<>();

		check(user, restResult, false);

		user.setEvpPassword(passwordEncoder.encode(user.getEvpPassword()));

		if (restResult.getStatus() == CustomHttpStatus.UNAUTHORIZED) {
			return restResult;
		}

		this.insertSelectiveBindCrt(user);
		restResult.setMessage("注册用户成功");
		return restResult;
	}

	/**
	 * 验证规则
	 *
	 * @param user
	 * @param isUpdate
	 * @return
	 */
	private void check(EvpUser user, ObjectResultResponse<Void> restResult, boolean isUpdate) {

		Example example = new Example(EvpUser.class).selectProperties("id","evpAccount", "phone");

		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("isDeleted", BooleanUtil.BOOLEAN_FALSE);
		criteria.andEqualTo("evpAccount", user.getEvpAccount());

		Example.Criteria criteria1 = example.or();
		criteria1.andEqualTo("isDeleted", BooleanUtil.BOOLEAN_FALSE);
		criteria1.andEqualTo("phone", user.getPhone());

		List<EvpUser> EvpUsers = this.selectByExample(example);

		if (EmptyUtil.isNotEmpty(EvpUsers)) {
			EvpUser EvpUser = EvpUsers.get(0);
			if (isUpdate) {
				if (StringUtil.equals(user.getEvpAccount(), EvpUser.getEvpAccount()) && !user.getId().equals(EvpUser.getId())) {
					// 表示正在进行更新操作的用户与非他的用户帐号冲突
					restResult.setStatus(CustomHttpStatus.UNAUTHORIZED);
					restResult.setMessage("该帐号已被注册");
					return;
				} else if (StringUtil.equals(user.getPhone(), EvpUser.getPhone()) && !user.getId()
					.equals(EvpUser.getId())) {
					restResult.setStatus(CustomHttpStatus.UNAUTHORIZED);
					restResult.setMessage("该手机号已存在");
					return;
				}
			} else {
				if (StringUtil.equals(user.getEvpAccount(), EvpUser.getEvpAccount())) {
					// 表示正在进行更新操作的用户与非他的用户帐号冲突
					restResult.setStatus(CustomHttpStatus.UNAUTHORIZED);
					restResult.setMessage("该帐号已被注册");
					return;
				} else if (StringUtil.equals(user.getPhone(), EvpUser.getPhone())) {
					restResult.setStatus(CustomHttpStatus.UNAUTHORIZED);
					restResult.setMessage("该手机号已存在");
					return;
				}
			}
		}
	}

	/**
	 * 更新单个对象
	 *
	 * @param user
	 * @return
	 */
	public ObjectResultResponse<Void> updatEvpUser(EvpUser user) {
		ObjectResultResponse<Void> restResult = new ObjectResultResponse<>();

		check(user, restResult, true);

		if (restResult.getStatus() == CustomHttpStatus.UNAUTHORIZED) {
			return restResult;
		}

		this.updateSelectiveByIdBindUpd(user);
		restResult.setMessage("更新用户成功");
		return restResult;
	}

	/**
	 * 删除单个对象
	 * @param id
	 * @return
	 */
	public ObjectResultResponse<Void> delUser(Integer id) {
		ObjectResultResponse<Void> restResult=new ObjectResultResponse<>();

		EvpUser user=new EvpUser();
		user.setId(id);
		user.setIsDeleted(BooleanUtil.BOOLEAN_TRUE);
		this.updateSelectiveByIdBindUpd(user);

		restResult.setMessage("删除帐号成功");
		return restResult;
	}

	/**
	 * 获取当前用户
	 * @return
	 */
    public EvpUser getCurrentUser(String username) {
		EvpUser evpUser = this.getUserByEAccount(username);
		evpUser.setEvpPassword(null);
		return evpUser;
    }

	/**
	 * 更新单个对象
	 *
	 * @param user
	 * @return
	 */
	public ObjectResultResponse<Void> updateUser(EvpUser user) {
		ObjectResultResponse<Void> restResult = new ObjectResultResponse<>();

		check(user, restResult, true);

		if (restResult.getStatus() == CustomHttpStatus.COMMON_ERROR) {
			return restResult;
		}

		this.updateSelectiveByIdBindUpd(user);
		restResult.setMessage("更新用户成功");
		return restResult;
	}

	/**
	 * 带事务添加记录
	 * @param user
	 */
	@Transactional
    public void insertUserWithTx(EvpUser user) {
    	this.insertSelectiveBindCrt(user);
    }

	/**
	 * 不带事务添加记录
	 * @param user
	 */
    public void insertUserWithoutTx(EvpUser user) {
    	this.insertSelectiveBindCrt(user);
    }
}